/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.component.cells.editors;

import cn.ac.nercis.pes.community.support.controls.cells.editors.base.EditorNodeBuilder;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.event.EventHandler;
import javafx.scene.control.TextArea;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.Region;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;

/**
 * 文本域编辑器
 * @author zpy
 * @version 1.0.0
 */
public class TextAreaEditorBuilder implements EditorNodeBuilder<String> {

    protected TextArea textArea;

    @Override
    public void startEdit() {
        if(Objects.nonNull(textArea)){
            Platform.runLater(() -> {
                textArea.selectAll();
                textArea.requestFocus();
            });
        }
    }

    @Override
    public void cancelEdit() {

    }

    @Override
    public void updateItem(String item, boolean empty) {
        if(Objects.nonNull(textArea)){
            Platform.runLater(() -> {
                textArea.selectAll();
                textArea.requestFocus();
            });
        }
    }

    @Override
    public Region createNode(String value, EventHandler<KeyEvent> eventHandler, ChangeListener<Boolean> changeListener) {
        textArea = value == null ? new TextArea() : new TextArea(enterProcess(value));
        textArea.setPromptText("输入内容说明");
        textArea.setOnKeyPressed(t->{
            if(t.getCode() == KeyCode.ESCAPE){
                eventHandler.handle(t);
            }else if(t.getCode() == KeyCode.TAB){
                eventHandler.handle(t);
            }
        });
        textArea.focusedProperty().addListener(changeListener);
        return textArea;
    }

    @Override
    public void setValue(String value) {
        textArea.setText(StringUtils.isEmpty(value) ? "" : enterProcess(value));
    }

    @Override
    public String getValue() {
        return textArea.getText();
    }

    @Override
    public void validateValue() throws Exception {
    }

    @Override
    public void nullEditorNode() {
        textArea = null;
    }

    private String enterProcess(String value){
        if(StringUtils.contains(value,"\\n")){
            return StringUtils.replace(value,"\\n","\n");
        }else{
            return value;
        }
    }
}